#############################
### R Function: fsQCA.sim ###
#############################

fsQCA.sim=function(dataset, depvar, indepvars, min.freq, max.freq, reps, explain, given.incl.cut0, given.incl.cut1, min){
  
  n.cut.list=c(min.freq:max.freq)
  
  fun.n.cut=function(x){
    out=as.data.frame(fsQCA.sim.inclcut(dataset=dataset, depvar=depvar, indepvars=indepvars, n.cut=x, reps=reps, explain=explain, min=min))
    return(out)
  }
  
  out=lapply(X=n.cut.list, FUN=fun.n.cut)
  results=rbind.fill(out)
  
  Configurations=do.call(paste, as.data.frame(results[,4:ncol(results)], stringsAsFactors=FALSE))
  Configurations=gsub(pattern=" NA", replacement="", x=Configurations)
  Configurations=gsub(pattern=" ", replacement=" + \n  ", x=Configurations)
  
  results=cbind(results[,1:2], paste("Frequency Threshold = ", results[,3], sep=""), Configurations)
  colnames(results)[3]="n.cut"
  results$incl.cut1.val=as.numeric(as.vector(results$incl.cut1.val))
  results$incl.cut0.val=as.numeric(as.vector(results$incl.cut0.val))
  
  plot=ggplot(data=results, aes(x=incl.cut0.val, y=incl.cut1.val, colour=Configurations))+geom_point()+scale_color_hue(c=150, l=60)+xlim(0,1)+ylim(0,1)+xlab(label="Maximum Sufficiency Inclusion Score")+ylab(label="Minimum Sufficiency Inclusion Score")+geom_point(x=given.incl.cut0, y=given.incl.cut1, shape=17, color="black", size=2)+guides(col=guide_legend(keyheight=2))+facet_wrap(~n.cut, ncol=2)
  
  return(list("results"=results, "plot"=plot))    
}

